var express = require('express');
var router = express.Router();


// 导入模型
const Administrator = require('../../model/Administrator')
// 用户模型
const uaerModel = require('../../model/uaerModel')


// 创建
router.post('/create', async function (req, res, next) {
    let body = {
        userId: req.body.userId,
        reason: req.body.reason,
        userName: req.body.userName,
        phone: req.body.phone,
    }
    const adminData = await Administrator.find({ userId: req.body.userId })
    if (adminData.length != 0) {
        res.send({
            code: 200,
            success: true,
            msg: "您已申请，正在审核中，请勿重复提交",
        })
        return
    }
    await Administrator.create(body).then((data) => {
        res.send({
            code: 200,
            success: true,
            msg: "申请中，等待审核",
            data,
        })
    }).catch((err) => {
        res.send({
            code: 500,
            success: false,
            msg: "申请失败",
            data: err
        })
    });
})
// 查询 管理员
router.post('/adminlist', async function (req, res, next) {
    if (req.body.status == 2) {
        const admindata = await Administrator.find().limit(req.body.pageSize).skip((req.body.pageIndex - 1) * req.body.pageSize)
        const adminCount = await Administrator.find()
        res.send({
            code: 200,
            success: true,
            msg: "待审核管理员查询成功",
            data: admindata,
            count: adminCount.length
        })
    } else {
        const admindata = await uaerModel.find({ Administrator: "1" }).limit(req.body.pageSize).skip((req.body.pageIndex - 1) * req.body.pageSize)
        const adminCount = await Administrator.find()
        res.send({
            code: 200,
            success: true,
            msg: "管理员查询成功",
            data: admindata,
            count: adminCount.length
        })
    }

})

// 审核管理员
router.post('/auditadmin', async function (req, res, next) {
    const admindata = await uaerModel.updateOne({
        userId: req.body.userId
    }, {
        $set: {
            Administrator: req.body.status,
        },
    })
    await Administrator.deleteOne({
        userId: req.body.userId
    })
    res.send({
        code: 200,
        success: true,
        msg: "审核成功",
        data: admindata,
    })
})


module.exports = router;